package com.aokang.footwear.common.serializer;

import com.aokang.footwear.common.properties.BizEnvProperties;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author chilei
 * @date 2024/3/5
 * 自定义序列化器
 */
@Component
public class CustomDomainSerializer extends JsonSerializer<String> implements ContextualSerializer {

    @Resource
    private BizEnvProperties bizEnvProperties;

    private String prefix;

    public CustomDomainSerializer() {
    }

    public CustomDomainSerializer(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (StringUtils.isNotBlank(value)) {
            gen.writeString(prefix + value);
        } else {
            gen.writeString(value);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        CustomDomain annotation = property.getAnnotation(CustomDomain.class);
        if (annotation != null) {
            // 如果前缀需要从配置文件中获取
            if (CustomDomain.FILE_PIC_URLS.equals(annotation.prefix())) {
                return new CustomDomainSerializer(bizEnvProperties.getFilePicUrl());
            }
            return new CustomDomainSerializer(annotation.prefix());
        }
        return this;
    }
}
